--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)
require "logGenerator"
require "nvm"

--参数配置文件初始化
nvm.init("config.lua", true)
--变量初始化
local slen, errInfo, sysTime, clientNo = string.len, "", "", nvm.get("info")[1]


--- MQTT客户端数据接收处理
-- @param mqttRClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttRClient)
function proc(mqttRClient)
    local result, data, receiveMsg, base64DecodeMsg, aesDecryptMsg, todo, clients
    while true do
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d", os.date("*t").year,
            os.date("*t").month, os.date("*t").day, os.date("*t").hour, os.date("*t").min, os.date("*t").sec)
        result, data = mqttRClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        -- 接收到数据
        if result then
            receiveMsg = data.payload
            base64DecodeMsg = crypto.base64_decode(receiveMsg, slen(receiveMsg))
            aesDecryptMsg = crypto.aes_decrypt("ECB", "PKCS5", base64DecodeMsg,
                "keson-123abcdefg")
            log.info("receiveMsgCMD", aesDecryptMsg)
            local tjsondata, resultMqtt, errinfo = json.decode(aesDecryptMsg)
            if resultMqtt and type(tjsondata) == "table" then
                if "guard" == data.topic then
                    todo = tjsondata["todo"]
                    if tjsondata["clients"] then
                        clients = tjsondata["clients"]
                    end
                    if "terminal" == todo then
                        if tjsondata["guardCmd"] then
                            if clientNo == clients[1] then
                                if "restart" == tjsondata["cmd"] then
                                    sys.restart("守护程序重启设备！")
                                end
                            end
                        end

                    end
                end
            else
                errInfo = errInfo .. "[" .. sysTime .. "]" .. "[json.decode error:]" .. errinfo .. "\n"
                logGenerator.generateLogTask(errInfo, "log")
                print("json.decode error", errinfo)
            end
        else
            break
        end
    end
    log.info("MQTT INMSG QU TASK  RESULT", result, "MQTT INMSG QU TASK DATA", data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
